#!/bin/bash

set -o errexit

# replace for your env
bind_vmuuid=44fcd7c3-bbee-e090-cae3-88d309e2ca6f
bind_data_dir=/export/lofs/mi-bind01/volumes/data

# 用法说明
function usage(){
  echo "usage:"
  echo "  $0 <options>"    
  echo "     -z|--zone <ZONE> dns zone, 如: itime.biz"
  echo "     -n|--name <NAME> dns名称, 如: mysql01"
  echo "     -t|--type <TYPE> dns类型, 值为 A 或 CNAME, 默认为 A" 
  echo "     -v|--value <VALUE> dns值"
  echo "        如果类型为 A, 则为 IP 地址"
  echo "        如果类型为 CNAME, 则为对应的CNAME值, 当CNAME值的zone为相同zone时, zone部分可以省略"
  echo ""   
  echo "     --help|-h 显示使用帮助"
  echo ""
  echo ""    
  echo "     使用示例："
  echo "          $0 -z itime.biz -n mysql01 -v 192.168.18.24"
  echo "              创建 A 记录 mysql01.itime.biz => 192.168.18.24"
  echo "          $0 -z itime.biz -t CNAME -n mysql -v mysql01"
  echo "          $0 -z itime.biz -t CNAME -n mysql -v mysql01.itime.biz"
  echo "              创建 A 记录 mysql.itime.biz => mysql01.itime.biz"
  echo "          $0 -h"
  echo "              显示命令使用帮助"
  exit
}

# 出错提示
function fatal(){
  echo ""
  echo "$1"
  exit 1
}


dns_zone=""
dns_type="A"
dns_name=""
dns_value=""

# 选项处理
while [[ $# -ge 1 ]]; do
    case $1 in        
        -z|--zone )
                dns_zone=$2
                shift 2
                ;;
        -t|--type )
                dns_type=$2
                shift 2
                ;;
        -n|--name )
                dns_name=$2
                shift 2
                ;;
        -v|--value )
                dns_value=$2
                shift 2
                ;;
        -os|--image-os )
                image_os=$2
                shift 2
                ;;
        -h|--help )
                usage
                ;;        
        * )
                echo "不支持的参数 $1"
                usage
                ;;
    esac
done


# the image name
[[ "${dns_name}" == "" ]] && fatal 'miss -n|--name <NAME>'  
[[ "${dns_value}" == "" ]] && fatal 'miss -v|--value <VALUE>'
[[ "${dns_zone}" == "" ]] && fatal 'miss -z|--zone <ZONE>'

if [ "${dns_type}" != "A" -a "${dns_type}" != "CNAME" ]; then
  fatal "不支持的 TYPE: ${dns_type}"
fi

zone_file=${bind_data_dir}/${dns_zone}.zone
[[ -f ${zone_file} ]] || fatal "不存在zone文件: ${zone_file}"

exists=$(grep "${dns_name}[[:space:]]" ${zone_file} || true)

first_line="; A"
dns_record="${dns_name}             IN      A       ${dns_value}"
if [ "dns_type" == "CNAME" ]; then
  first_line="; CNAME"
  dns_record="${dns_name}             IN      CNAME       ${dns_value}"
fi

if [ "${exists}" == "" ]; then
  first_line_exists=$(grep "${first_line}" ${zone_file} || true)
  if [ "${first_line_exists}" == "" ]; then
    gsed -i "\$a${dns_record}" ${zone_file}
  else
    sed -i "" "/${first_line}/a \\
${dns_record}\\
" ${zone_file}
  fi
else
  sed -i "" "s/${dns_name}[[:space:]].*/${dns_record}/" ${zone_file}
fi

zlogin ${bind_vmuuid} svcadm restart pkgsrc/bind